package com.whoimi.common.service.impl;

import com.whoimi.common.service.WeComBotService;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Collections;
import java.util.List;
import java.util.Optional;

@Service
public class WeComBotServiceImpl implements WeComBotService {
    private static final Logger log = LoggerFactory.getLogger(WeComBotServiceImpl.class);
    @Resource
    private RestTemplate restTemplate;

    @Value("${weComBot.url}")
    private String weComBotUrl;

    @Value("${weComBot.key-notify}")
    private String weComBotKeyNotify;


    @Override
    public ResponseEntity<String> botSend(List<String> phones, String context) {
        return this.botSend(phones, context, weComBotUrl + weComBotKeyNotify);
    }

    @Override
    public ResponseEntity<String> botSend(String context) {
        return this.botSend(Collections.singletonList("@all"), context, weComBotUrl + weComBotKeyNotify);
    }

    @Override
    public ResponseEntity<String> botSend(List<String> phones, String context, String botKey) {
        ResponseEntity<String> stringResponseEntity = null;
        try {
            WeixinBotParams weixinBotParams = new WeixinBotParams("text", new Text(context, null, phones));
            log.info(weixinBotParams.toString());
            String url = Optional.ofNullable(botKey).filter(s -> !s.trim().isEmpty()).orElse(weComBotUrl + weComBotKeyNotify);
            stringResponseEntity = restTemplate.postForEntity(url, weixinBotParams, String.class);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return stringResponseEntity;
    }

    record WeixinBotParams(String msgtype, Text text) {
    }

    record Text(String content, List<String> mentioned_list, List<String> mentioned_mobile_list) {
    }
}
